package pub.devrel.easypermissions;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.agp.window.dialog.IDialog;
import ohos.app.AbilityContext;
import pub.devrel.easypermissions.helper.PermissionHelper;

import java.util.Arrays;

/**
 * Click listener for either {@link RationaleDialogFragment} or {@link RationaleDialogFragmentCompat}.
 */
class RationaleDialogClickListener implements IDialog.ClickedListener {

    private Object mHost;
    private RationaleDialogConfig mConfig;
    private EasyPermissions.PermissionCallbacks mCallbacks;
    private EasyPermissions.RationaleCallbacks mRationaleCallbacks;

    RationaleDialogClickListener(AbilityContext compatDialogFragment,
                                 RationaleDialogConfig config,
                                 EasyPermissions.PermissionCallbacks callbacks,
                                 EasyPermissions.RationaleCallbacks rationaleCallbacks) {
        mHost = compatDialogFragment;

        mConfig = config;
        mCallbacks = callbacks;
        mRationaleCallbacks = rationaleCallbacks;

    }

    RationaleDialogClickListener(RationaleDialogFragment dialogFragment,
                                 RationaleDialogConfig config,
                                 EasyPermissions.PermissionCallbacks callbacks,
                                 EasyPermissions.RationaleCallbacks dialogCallback) {

        mHost = dialogFragment.getFractionAbility();

        mConfig = config;
        mCallbacks = callbacks;
        mRationaleCallbacks = dialogCallback;
    }

    @Override
    public void onClick(IDialog dialog, int which) {
        int requestCode = mConfig.requestCode;
        if (which == IDialog.BUTTON3) {
            String[] permissions = mConfig.permissions;
            if (mRationaleCallbacks != null) {
                mRationaleCallbacks.onRationaleAccepted(requestCode);
            }
            if (mHost instanceof Fraction) {
                PermissionHelper.newInstance((Fraction) mHost).directRequestPermissions(requestCode, permissions);
            } else if (mHost instanceof Ability) {
                PermissionHelper.newInstance((Ability) mHost).directRequestPermissions(requestCode, permissions);
            } else {
                throw new RuntimeException("Host must be an Ability or Fragment!");
            }
        } else {
            if (mRationaleCallbacks != null) {
                mRationaleCallbacks.onRationaleDenied(requestCode);
            }
            notifyPermissionDenied();
        }
    }

    private void notifyPermissionDenied() {
        if (mCallbacks != null) {
            mCallbacks.onPermissionsDenied(mConfig.requestCode, Arrays.asList(mConfig.permissions));
        }
    }

}
